

/**
 * jsonui
 * @type {{}}
 */
var jsonui = {};

/**
 * jsonui-解析器
 * @type {{}}
 */
jsonui.parser = {};

/**
 * jsonui-解析器-json操作
 * @type {{contain: jsonui.parser.json.contain, isObject: (function(*): boolean), merge: (function(*=, *=): {}), count: (function(*): number), isString: jsonui.parser.json.isString}}
 */
jsonui.parser.json = {
    /**
     * 查询json中是否出现值(仅一维)
     * @param arr
     * @param value
     * @returns {boolean}
     */
    contain: function (arr = [], value = "") {
        for (let index in arr) {
            if (arr[index] === value) {
                return true;
            }
        }
        return false;
    },
    /**
     * 判断是否是json字符串
     * @param str
     * @returns {boolean}
     */
    isString: function (str) {
        if (typeof str == "string") {
            try {
                var obj = JSON.parse(str);
                if (typeof obj == "object" && obj) {
                    return true;
                } else {
                    return false;
                }
            } catch (e) {
                return false;
            }
        }
        return false;
    },
    /**
     * 判断是否是json对象
     * @param data
     * @returns {boolean}
     */
    isObject: function (data) {
        return typeof (data) == "object";
    },
    /**
     * 统计json总数
     * 解决除[]json外，{}json无法使用length属性问题
     * @param json
     * @returns {number}
     */
    count: function (json) {
        var count = 0;
        for (var i in json) {
            count++;
        }
        return count;
    },
    /**
     * 合并json
     * 也可用于删除json唯一内存，前提是后一个参数json要有数据
     * 用此方法删除内存可以解决json里面带有函数的问题，如果用转字符串的方式删除内存，则会遗漏函数
     * @param obj
     * @param obj1
     * @returns {{}}
     */
    merge: function (obj = {}, obj1 = {}) {
        for (var i in obj1) {
            obj[i] = obj1[i];
        }
        return obj;
    }
};

/**
 * jsonui-解析器-api
 * @type {{ajax: jsonui.parser.api.ajax}}
 */
jsonui.parser.api = {
    /**
     * ajax
     * @param param
     */
    ajax: function (param = {}) {
        //合并参数
        param = jsonui.parser.json.merge({
            url: "",
            method: "GET",
            headers: {},
            data: {},
            dataType: "json",
            timeout: 60000,
            success: function (result) {
            },
            error: function (msg) {
                layer.msg(msg);
            }
        }, param);

        //网络请求
        var result = layui.jquery.ajax({
            type: param.method,
            url: param.url,
            data: param.data,
            headers: param.headers,
            async: true,
            cache: false,
            dataType: "text",
            timeout: param.timeout,
            success: function (result) {
                //解析JSON
                if (param.dataType == "json") {
                    //如果不是json字符串
                    if (!jsonui.parser.json.isString(result)) {
                        param.error("不是json");
                        return false;
                    }
                    //转换为json对象
                    result = JSON.parse(result);

                    //判断json必须的字段
                    if (!result.hasOwnProperty("code") || !result.hasOwnProperty("msg")) {
                        param.error("json缺少必须字段");
                        return false;
                    }

                    //如果code中报错
                    if (result.code != 0) {
                        param.error("错误码：" + result.code + "；描述：" + result.msg);
                        return false;
                    }
                } else {
                    //未定义的预期返回格式
                    //比如text等格式，需要原样返回
                }
                param.success(result);
            },
            error: function (data, status, e) {
                param.error(data.statusText);
            }
        });
    }
};

/**
 * jsonui-解析器-工具
 * @type {{getModule: jsonui.parser.tool.getModule, getUrl: (function(): string), getQuery: jsonui.parser.tool.getQuery, createCss: jsonui.parser.tool.createCss, createTpl: jsonui.parser.tool.createTpl}}
 */
jsonui.parser.tool = {
    /**
     * 获取jsonui所在地址
     * @returns {string}
     */
    getUrl: function () {
        let url = document.currentScript.src;
        let url_arr = url.split("/");
        url = "";
        layui.each(url_arr, function (index, item) {
            if (index < url_arr.length - 1) {
                url += item + "/";
            }
        });
        return url;
    },
    /**
     * 获取url参数
     * @param variable
     * @returns {string}
     */
    getQuery: function (variable) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            if (pair[0] == variable) {
                return pair[1];
            }
        }
        return "";
    },
    /**
     * 获取元素最近的上层module
     * @param elem 元素
     * @param module_name module名称(为空直接取距离最近的module)
     * @returns {{}}
     */
    getModule: function (elem, module_name = "") {
        //module标准四元素：name,data,index,elem
        let module = {};
        module.elem = false;
        //获取当前元素的上层所有module
        let modules = elem.parents(".jsonui-module");
        let modules_arr = [];
        //如果当前元素就是module
        if (elem.attr("class") == "jsonui-module") {
            modules_arr.push(elem);
        }
        //循环上层module
        layui.each(modules, function (index, item) {
            modules_arr.push(modules.eq(index));
        });
        //查找module
        layui.each(modules_arr, function (index, item) {
            if (module.elem === false) {
                //直接取最近的module
                if (!module_name) {
                    module.elem = item;
                }
                //根据指定的module名称取最近的module
                else {
                    let this_index_arr = item.attr("index").split(",");
                    let this_module_name = this_index_arr[this_index_arr.length - 1];
                    if (this_module_name == module_name) {
                        module.elem = item;
                    }
                }
            }
        });

        //如果没查找到module
        if (module.elem === false) {
            return false;
        }

        //获取module位置
        module.index = "";
        let parent_indexs = module.elem.parents("[index]");
        for (let index = parent_indexs.length - 1; index >= 0; index--) {
            let item = parent_indexs.eq(index);
            module.index += item.attr("index") + ",";
        }
        module.index += module.elem.attr("index");

        //获取module数据
        let index_arr = module.index.split(",");
        module.data = jsonui;
        module.name = "";
        layui.each(index_arr, function (index, item) {
            module.data = module.data[item];
            module.name = item;
        });
        return module;
    },
    /**
     * 获取随机数
     * @param n
     * @returns {string}
     */
    getRand: function (n) {
        var rnd = "";
        for (var i = 0; i < n; i++)
            rnd += Math.floor(Math.random() * 10);
        return rnd;
    },
    /**
     * 创建css
     * @param content
     */
    createCss: function (content) {
        layui.jquery("#jsonui-style style").append(content);
    },
    /**
     * 创建tpl
     * @param content
     */
    createTpl: function (content) {
        layui.jquery("#jsonui-tpl").append(content);
    },
};


/**
 * jsonui-解析器-配置
 * @type {{grid: [string, string, string], edition: string, gridDom: [string, string], url: string}}
 */
jsonui.parser.config = {
    url: jsonui.parser.tool.getUrl(),
    edition: "2.0.0",
    grid: ["result", "row", "col"],
    gridDom: ["row", "col"],
};

/**
 * jsonui-解析器-打开
 * @type {{init: jsonui.parser.open.init, w: {}, go: jsonui.parser.open.go}}
 */
jsonui.parser.open = {
    /**
     * 窗口参数
     */
    w: {},
    /**
     * 初始化函数
     * @param w
     */
    init: function (w = {}) {
        this.w = w;
        layui.jquery(function () {
            layui.use(["laytpl"], function () {
                jsonui.parser.open.go();
            });
        });
    },
    /**
     * go
     * @param w
     */
    go: function () {
        let w = this.w;
        //删除唯一内存
        w = JSON.parse(JSON.stringify(w));
        //缺省target
        w.target = (w.hasOwnProperty("target")) ? w.target : "load";
        switch (w.target) {
            case "load":
                //直接使用数据
                if (jsonui.parser.json.isObject(w.content)) {
                    //渲染
                    jsonui.parser.render.init(w.content);
                }
                //api接口
                else {
                    jsonui.parser.api.ajax({
                        url: w.content,
                        success: function (result) {
                            //渲染
                            jsonui.parser.render.init(result);
                        }
                    });
                }
                break;
            case "self":
                //跳转打开
                w.content = window.location.pathname + "?content=" + encodeURIComponent(w.content);
                window.location.href = w.content;
                break;
            case "blank":
                //新窗口打开
                layui.msg("暂不支持blank");
                break;
            case "window":
                //弹窗打开
                if (w.type == 2) {
                    w.content = window.location.pathname + "?content=" + encodeURIComponent(w.content);
                }
                layer.open(w);
                break;
            default:
                layer.msg("target error");
                break;
        }
    }
};

/**
 * jsonui-解析器-渲染
 * @type {{useModule: [], findModule: jsonui.parser.render.findModule, init: jsonui.parser.render.init, createBasicDom: jsonui.parser.render.createBasicDom, renderModule: {init: jsonui.parser.render.renderModule.init, initModule: []}}}
 */
jsonui.parser.render = {

    //使用模块
    useModule: [],

    /**
     * 初始化渲染
     * @param content
     */
    init: function (content = {}) {

        console.time("open");

        //舍弃非解析器以外的对象
        jsonui = {
            parser: jsonui.parser
        };
        //合并json
        jsonui = jsonui.parser.json.merge(jsonui, content);

        //初始化使用模块
        jsonui.parser.render.useModule = [];

        //创建基础dom
        jsonui.parser.render.createBasicDom();

        //发现模块
        jsonui.parser.render.findModule({
            data: jsonui,
            elem: layui.jquery("#jsonui"),
        });

        //渲染模块
        jsonui.parser.render.renderModule.init();
    },

    /**
     * 创建基础dom
     */
    createBasicDom: function () {
        //创建jsonui元素
        if (!layui.jquery("#jsonui").size()) {
            layui.jquery("body").append("<div id=\"jsonui\"></div>");
        }
        //创建style元素
        if (!layui.jquery("#jsonui-style").size()) {
            layui.jquery("#jsonui").after("<div id=\"jsonui-style\"><style type=\"text/css\">#jsonui{}.layui-row{margin-left:0 !important;margin-right:0 !important;}.layui-row > *:first-child{padding-left:0;}.layui-row > *:last-child{padding-right:0;}</style></div>");
        }
        //创建tpl元素
        if (!layui.jquery("#jsonui-tpl").size()) {
            layui.jquery("#jsonui").after("<div id=\"jsonui-tpl\"></div>");
        }

        //清空jsonui元素
        layui.jquery("#jsonui").html("");
    },


    /**
     * 发现模块
     * 同时此函数也提供给创建模块dom使用
     * @param param 参数
     */
    findModule: function (param = {}) {

        //合并参数
        param = jsonui.parser.json.merge({
            data: [], //发现数据源
            index: "", //数据索引
            elem: false, //元素对象(模块填充到此元素)
            isFind: true //是否需要发现模块
        }, param);

        //循环
        layui.each(param.data, function (index, item) {

            //如果item不是json对象
            if (!jsonui.parser.json.isObject(item)) {
                //直接跳过
                return false;
            }

            //遇到模块
            if (index == "module" && param.isFind === true) {
                layui.each(item, function (index1, item1) {
                    //console.log("1——发现模块：" + index1 + ":" + jsonui.parser.render.useModule.length);

                    //新的index索引
                    let new_data_index = param.index;
                    new_data_index += (new_data_index) ? "," : "";
                    new_data_index += "module," + index1;
                    //属性组
                    let attrs = " index=\"" + new_data_index + "\" class=\"jsonui-module\"";
                    //如果有模块头信息
                    if (item1.hasOwnProperty("header")) {
                        if (item1.header.hasOwnProperty("elem")) {
                            attrs += " elem=\"" + item1.header.elem + "\"";
                        }
                        if (item1.header.hasOwnProperty("display") && item1.header.display === false) {
                            attrs += " style=\"display:none;\"";
                        }
                    }
                    //创建元素
                    param.elem.append("<div" + attrs + "></div>");

                    //添加使用模块
                    jsonui.parser.render.useModule.push({
                        "name": index1,
                        "data": item1,
                        "index": new_data_index,
                        "elem": param.elem.children(".jsonui-module[index=\"" + new_data_index + "\"]"),
                    });
                });
            }
            //遇到栅格
            else if (Number.isInteger(index) || jsonui.parser.json.contain(jsonui.parser.config.grid, index)) {
                //新的index索引
                let new_data_index = param.index;
                new_data_index += (new_data_index) ? "," : "";
                new_data_index += index;

                //新元素(默认为当前元素)
                let new_elem = param.elem;
                //创建新元素
                if (jsonui.parser.json.contain(jsonui.parser.config.gridDom, index)) {
                    //名称
                    let name = "div[index=\"" + new_data_index + "\"]";
                    //属性组
                    let attrs = " index=\"" + new_data_index + "\"";
                    //class
                    let class_value = " class=\"layui-" + index;
                    //如果有属性
                    if (item.hasOwnProperty("attr")) {
                        //style
                        let style_value = "";
                        switch (index) {
                            case "row":
                                layui.each(item.attr, function (index1, item1) {
                                    switch (index1) {
                                        case "space":
                                            class_value += " layui-col-space" + item1;
                                            break;
                                        default:
                                            break;
                                    }
                                });
                                break;
                            case "col":
                                layui.each(item.attr, function (index1, item1) {

                                    switch (index1) {
                                        case "xs":
                                            class_value += " layui-col-xs" + item1;
                                            break;
                                        case "sm":
                                            class_value += " layui-col-sm" + item1;
                                            break;
                                        case "md":
                                            class_value += " layui-col-md" + item1;
                                            break;
                                        case "xsOffset":
                                            class_value += " layui-col-xs-offset" + item1;
                                            break;
                                        case "smOffset":
                                            class_value += " layui-col-sm-offset" + item1;
                                            break;
                                        case "mdOffset":
                                            class_value += " layui-col-md-offset" + item1;
                                            break;
                                        case "xsStyle":
                                            style_value += "#jsonui " + name + "{" + item1 + "}";
                                            break;
                                        case "smStyle":
                                            style_value += "@media screen and (min-width:768px){#jsonui " + name + "{" + item1 + "}" + "}";
                                            break;
                                        case "mdStyle":
                                            //获取css名称
                                            let css_name = jsonui.parser.tool.getRand(10);
                                            attrs += " css_name=\"" + css_name + "\"";
                                            css_name = name + "[css_name=\"" + css_name + "\"]";
                                            style_value += "@media screen and (min-width:992px){#jsonui " + css_name + "{" + item1 + "}" + "}";
                                            break;
                                        default:
                                            break;
                                    }
                                });
                                break;
                            default:
                                break;
                        }
                        //set style
                        if (style_value) {
                            layui.jquery("#jsonui-style style").append(style_value);
                        }
                    }
                    class_value += "\"";
                    attrs += class_value;

                    //创建元素
                    param.elem.append("<div" + attrs + "></div>");
                    //选中元素
                    new_elem = param.elem.children(name);
                    //清空index索引
                    new_data_index = "";
                }
                //继续发现模块
                jsonui.parser.render.findModule({
                    data: item,
                    index: new_data_index,
                    elem: new_elem,
                });
            }
        });
    },

    /**
     * 渲染模块
     */
    renderModule: {

        //初始化过的模块
        initModule: [],

        //初始化
        init: function () {

            //调用的模块函数：
            //1、init,初始化模块,生命周期开始时,每个模块调用一次,同模块不会重复调用
            //2、render,渲染模块,每次渲染模块就会调用一次,使用相同模块会调用多次
            //3、success,渲染模块完成,所有模块渲染完成后，会将已渲染的模块按渲染顺序调用一次success函数
            //4、setValue,模块设置默认值,模块放在form模块下级时,当form模块触发了success函数，会将form模块的所有下级模块按顺序调用一次setValue函数

            //循环发现的模块
            layui.each(jsonui.parser.render.useModule, function (index, item) {
                //初始化模块
                if (!jsonui.parser.json.contain(jsonui.parser.render.renderModule.initModule, item.name)) {
                    //console.log("2————————初始化模块：" + item.name + ":" + index);
                    //推到初始化过的模块(每个模块不管用了多少次都只初始化一次)
                    jsonui.parser.render.renderModule.initModule.push(item.name);
                    //调用模块init函数
                    console.log(item.name);
                    if (jsonui.parser.module[item.name].hasOwnProperty("init")) {
                        jsonui.parser.module[item.name].init();
                    }
                }
                //渲染模块
                if (!item.hasOwnProperty("renderCallStatus")) {
                    //console.log("3————————————————渲染模块：" + item.name + ":" + index);
                    //调用模块render函数
                    if (jsonui.parser.module[item.name].hasOwnProperty("render")) {
                        jsonui.parser.module[item.name].render(item);
                    }
                    //console.log("4————————————————————————————————渲染模块完成：" + item.name + ":" + index);
                }
            });

            console.log("所有模块渲染完成，确认完毕，发现模块数量：" + jsonui.parser.render.useModule.length + "，发现模块如下：");
            console.log(JSON.parse(JSON.stringify(jsonui.parser.render.useModule)));

            //循环发现的模块
            layui.each(jsonui.parser.render.useModule, function (index, item) {
                //调用模块success函数
                if (jsonui.parser.module[item.name].hasOwnProperty("success")) {
                    jsonui.parser.module[item.name].success(item);
                }
            });

            //console.log(jsonui);
            console.timeEnd("open");
        }
    }
};

/**
 * jsonui-解析器-模块
 * 渲染方式：jsonui.parser.module.名称.render
 * @type {{}}
 */
jsonui.parser.module = {}


/**
 * jsonui-解析器-事件
 * @type {{init: jsonui.parser.event.init, re: jsonui.parser.event.re, action: {setModuleHeader: jsonui.parser.event.action.setModuleHeader, window: jsonui.parser.event.action.window, close: jsonui.parser.event.action.close, tableRender: jsonui.parser.event.action.tableRender}}}
 */
jsonui.parser.event = {
    //初始化
    init: function (param = {}) {
        layui.each(param, function (index, item) {
            jsonui.parser.event.re(item);
        });
    },
    //递归事件到达页面
    re: function (param = {}, level = 0) {
        //寻找层级方法：
        //1、递归递加向上找，缺点：如果向上找完了，级别不够预设的，就会在最顶级执行，正在使用
        //2、每打开一个窗口时记录层级，需要向上找时判断页面的层级，尚未发现缺点
        //页面层级到达时
        if (param.level == level || param.level == -1) {

            //如果事件有动作
            if (param.hasOwnProperty("action")) {
                //循环动作
                layui.each(param.action, function (index, item) {
                    console.log("执行：" + param.level + "层级；动作：" + index + "；页面链接：" + window.location.href);
                    //执行动作
                    jsonui.parser.event.action[index](param.level, item);
                });
            }
            //执行一次就终止
            return true;
        }

        //向上层级
        level++;
        //继续访问父窗口
        window.parent.jsonui.parser.event.re(param, level);
    },
    //动作
    action: {
        /**
         * 关闭窗口
         * @param level
         * @param param
         */
        close: function (level, param = {}) {
            let window_obj = (level === -1) ? window.top : window.parent;
            window_obj.layer.close(window_obj.layer.getFrameIndex(window.name));
        },
        /**
         * 打开页面
         * @param level
         * @param param
         */
        window: function (level, param = {}) {
            let window_obj = (level === -1) ? window.top : window;
            window_obj.jsonui.parser.open.init(param);
        },
        /**
         * 刷新页面
         * @param level
         * @param param
         */
        renovate: function (level, param = {}) {
            window.location.href = window.location.href;
        },
        /**
         * 设置模块头信息
         * @param level
         * @param param
         */
        setModuleHeader: function (level, param = {}) {
            let window_obj = (level === -1) ? window.top : window;
            layui.each(window_obj.jsonui.parser.render.useModule, function (index, item) {
                if (!item.data.hasOwnProperty("header") || !item.data.header.hasOwnProperty("elem")) {
                    return false;
                }
                if (item.data.header.elem == param.elem) {
                    if (param.hasOwnProperty("display")) {
                        let elem = layui.jquery(".jsonui-module[elem=\"" + param.elem + "\"]");
                        if (param.display == true) {
                            elem.css("display", "block");
                        } else {
                            elem.css("display", "none");
                        }
                    }
                }
            });
        },
        /**
         * 数据表格重载
         * @param level
         * @param param
         */
        tableRender: function (level, param = {}) {
            let window_obj = (level === -1) ? window.top : window;
            window_obj.table_display_render(param.elem);
        },
    }
};


/**
 * exports jsonui
 */
layui.define(function (exports) {
    exports('jsonui', jsonui);
});


jsonui.parser.module.adminBox = {
    init: function () {
        jsonui.parser.tool.createCss(`
.admin-box{}
.admin-box-left{background: #fff;position: fixed;z-index: 1;left: 0;top: 0;width: 210px;height: 100%;-webkit-box-shadow: 2px 0 8px 0 rgb(29 35 41 / 5%);box-shadow: 2px 0 8px 0 rgb(29 35 41 / 5%);overflow-y: auto;}
.admin-box-left-switch{position: absolute;z-index: 1;margin: 10px 0 0 220px;cursor: pointer;}
.admin-box-left-switch i{display:block;margin:3px 0 0 0;width:20px;height:2px;background:#ccc;border-radius:2px;}
.admin-box-left-switch:hover i{background:#383838;}
.admin-box-body{padding:0 0 0 210px;}
        `);
        jsonui.parser.tool.createTpl(`
<script type="text/html" id="tpl-adminBox">

<div class="admin-box">
    <div class="admin-box-left"></div>
    <div class="admin-box-left-switch"><i></i><i></i><i></i><i></i></div>
    <div class="admin-box-body"></div>
</div>

</script>
        `);
    },
    render: function (module) {
        layui.use(["laytpl"], function () {
            layui.laytpl(layui.jquery("#tpl-adminBox").html()).render(module.data, function (html) {
                module.elem.html(html);
                if(module.data.hasOwnProperty("content")){
                    if(module.data.content.hasOwnProperty("left")){
                        //发现模块
                        jsonui.parser.render.findModule({
                            data: module.data.content.left,
                            index: "content,left",
                            elem: module.elem.children(".admin-box").children(".admin-box-left")
                        });
                    }
                    if(module.data.content.hasOwnProperty("body")){
                        //发现模块
                        jsonui.parser.render.findModule({
                            data: module.data.content.body,
                            index: "content,body",
                            elem: module.elem.children(".admin-box").children(".admin-box-body")
                        });
                    }
                }
            });
        });
    }
};


jsonui.parser.module.albumBrowse = {
    init: function () {
        jsonui.parser.tool.createCss(`
.jsonui_albumBrowse{display:table;width:100%;}
.jsonui_albumBrowse li{float:left;margin:10px 10px 0 0;border: 1px solid #eee;padding:10px;}
.jsonui_albumBrowse li img{min-width:60px;min-height:60px;}
        `);
        jsonui.parser.tool.createTpl(`
<script type="text/html" id="tpl-albumBrowse">
    <div class="jsonui_albumBrowse" id="{{d.id}}">
         {{#
            let this_style = "";
            if(d.hasOwnProperty("width")){
                this_style += "width:"+d.width+"px;";
            }
            if(d.hasOwnProperty("height")){
                this_style += "height:"+d.height+"px;";
            }
            layui.each(d.data, function(index, item){ 
         }}
         <li>
            <img 
            layer-pid="{{index}}"
            layer-src="{{item.url}}"
            
            {{# if(d.hasOwnProperty("thumbnail")){ }}
            src="{{item.thumbnail}}" 
            {{# }else{ }}
            src="{{item.url}}" 
            {{# } }}
            
            {{# if(d.hasOwnProperty("title")){ }}
            alt="{{item.title}}"
            {{# } }}
            
            style="{{this_style}}"
             />
         </li>
         {{# }); }}
    </div>
</script>
        `);
    },
    render: function (module) {

    },
    setValue: function (module, values) {
        if (values.hasOwnProperty(module.data.name)) {
            layui.use(["laytpl"], function () {

                let d = module.data;
                d.id = "jsonui_albumBrowse_" + jsonui.parser.tool.getRand(10);
                d.data = values[module.data.name];

                layui.laytpl(layui.jquery("#tpl-albumBrowse").html()).render(d, function (html) {
                    module.elem.html(html);

                    //调用示例
                    layer.photos({
                        photos: '#' + d.id,
                        anim: 5
                    });
                });
            });
        }
    }
};


jsonui.parser.module.blockQuote = {

    init: function () {

        jsonui.parser.tool.createCss(`
.layui-elem-quote{
    margin:0;
}
        `);
        jsonui.parser.tool.createTpl(`
<script type="text/html" id="tpl-blockQuote">
    {{# 
        let attr_class = "layui-elem-quote";
        if(d.hasOwnProperty("attr") && d.attr.hasOwnProperty("nm")){
            attr_class += " layui-quote-nm";
        }
    }}
    <blockquote class="{{attr_class}}">{{# if(d.hasOwnProperty("content")){ }}{{d.content}}{{# } }}</blockquote>
</script>
        `);

    },

    render: function (module) {
        layui.use(["laytpl"], function () {
            layui.laytpl(layui.jquery("#tpl-blockQuote").html()).render(module.data, function (html) {
                module.elem.html(html);
                //更新elem
                module.elem = module.elem.children("blockquote");


                //发现模块
                jsonui.parser.render.findModule({
                    data: module.data,
                    index: module.index,
                    elem: module.elem
                });
            });
        });
    }


};


jsonui.parser.module.button = {

    init:function (){
        jsonui.parser.tool.createCss(`
.module-form{
    padding:15px;
}
.layui-btn-lime{
    display: inline-block;
    margin: 0 15px 0 0;
    border: 1px solid #a8c285;
    background-image: linear-gradient(to bottom,#cff483, #a1d864);
    border-radius: 3px;
    padding: 0 10px;
    min-width:80px;
    height: 32px;
    line-height: 30px;
    text-align: center;
    font-size: 15px;
    color: #507a14;
}
.layui-btn-lime:hover{
    color: #507a14;
    opacity: 0.8;
}
.layui-btn-lime-reset{
    background-image: linear-gradient(to bottom,#fcfcfc, #f0f0f0);
}
        `);
        jsonui.parser.tool.createTpl(`
<script type="text/html" id="tpl-button">
    {{# if(d.filter=="submit"){ }}
    <button type="submit" class="layui-btn layui-btn-lime" lay-filter="form_botton" lay-submit="">{{d.title}}</button>
    {{# } else if(d.filter=="search"){ }}
    <button type="submit" class="layui-btn layui-btn-lime" lay-filter="form_botton" lay-submit="">{{d.title}}</button>
    {{# } else if(d.filter=="reset"){ }}
    <button type="reset" class="layui-btn layui-btn-lime layui-btn-lime-reset" lay-filter="form_botton" lay-submit="">
        {{d.title}}
    </button>
    {{# } else{ }}
    <button type="button" class="layui-btn layui-btn-lime layui-btn-lime-reset">{{d.title}}</button>
    {{# } }}
</script>
        `);
    },

    render: function (module) {
        layui.use(["laytpl"], function () {
            layui.laytpl(layui.jquery("#tpl-button").html()).render(module.data, function (html) {
                module.elem.html(html);
            });
        });
    },
    success: function (module) {
        layui.use(["form"], function () {
            layui.form.on("submit(form_botton)", function (data) {
                //取得按钮模块
                let botton_module = jsonui.parser.tool.getModule(layui.jquery(data.elem));

                switch (botton_module.data.filter) {
                    case "submit":
                        //表单提交
                        form_display_submit(botton_module.data, data.field);
                        break;
                    case "search":
                        //搜索提交
                        form_display_search(botton_module.data, data.field);
                        break;
                    case "reset":
                        //重置
                        if (confirm("确定" + botton_module.data.title + "吗？")) {
                            //表单中如果有非layui组件需要在这里手动重置
                            //调用重置函数
                            //允许重置
                            return true;
                        }
                        break;
                    default:
                        alert("filter error");
                        break;
                }
                return false;
            });
        });
    }
};





/**
 * 表单-过滤空数据
 * 避免空数据提交到接口
 * @param data
 * @returns {{}}
 */
function form_display_filter_null(data) {
    var new_data = {};
    for (var i in data) {
        if (data[i].length > 0) {
            new_data[i] = data[i];
        }
    }
    return new_data;
}

/**
 * 表单-提交
 * @param button 按钮数据
 * @param data 用户输入的表单数据
 */
function form_display_submit(button, data) {

    //表单-过滤空数据
    data = form_display_filter_null(data);

    let index = layer.load(1, {shade: [0.1, "#fff"]});
    jsonui.parser.api.ajax(jsonui.parser.json.merge({
        url: "",
        method: "POST",
        data: data,
        success: function (result) {
            layer.close(index);

            let index1 = layer.alert(result.msg, {
                skin: 'layui-layer-molv'
                , closeBtn: 0
            }, function () {
                layer.close(index1);

                //表单提交后-事件
                jsonui.parser.event.init(button.successAfter);
            });

        },
        error: function (msg) {
            layer.close(index);
            layer.msg(msg);
        }
    }, button));
}

/**
 * 表单-搜索提交
 * @param button 按钮json数据
 * @param data 用户输入的表单数据
 * @returns {boolean}
 */
function form_display_search(button, data) {

    //表单-过滤空数据
    data = form_display_filter_null(data);

    if(typeof table_display_param==="undefined"){
        layer.msg("未发现数据表格");
        return false;
    }

    //找到搜索按钮属性elem指定的数据表格
    layui.each(table_display_param,function(index,item){
        if(item.elem==button.elem){
            //删除唯一内存
            item = JSON.parse(JSON.stringify(item));
            //合并参数
            item.where = jsonui.parser.json.merge(item.where, data);

            //创建表格
            table_display_create(item,item.moduleIndex);
        }
    });
}


jsonui.parser.module.checkbox = {

    init: function () {
        jsonui.parser.tool.createCss(`
.jsonui_checkbox{
    
}
.jsonui_checkbox ul{
    display:table;
}
.jsonui_checkbox ul li{
    float:left;
    margin-top:9px;
}
.jsonui_checkbox ul li a{
    display:table;
    cursor:pointer;
}
.jsonui_checkbox ul li a span{
    position: absolute;
    width: 16px;
    height: 16px;
    line-height:16px;
    line-height: 16px;
    border: 1px solid #d2d2d2;
    font-size: 12px;
    border-radius: 2px;
    background-color: #fff;
    text-align: center;
}
.jsonui_checkbox ul li a:hover span{
    border-color: #5FB878;
}
.jsonui_checkbox ul li a b{
    display:block;
    font-weight: normal;
    padding-right: 15px;
    line-height: 18px;
    color: #666;
    padding-left:24px;
    font-size: 14px;
}
.jsonui_checkbox ul li a[disabled="true"]{
    cursor: not-allowed;
    opacity:0.5;
}
.jsonui_checkbox ul li a[disabled="true"]:hover span{
    border-color: #d2d2d2;
}
.jsonui_checkbox ul li a span.layui-icon-ok{
    border-color: #5FB878;
    background:#5FB878;
    color: #fff;
}
        `);
        jsonui.parser.tool.createTpl(`
<script type="text/html" id="tpl-checkbox">
    <div class="jsonui_checkbox">
        <input type="hidden" name="{{d.name}}" />
        <ul>
            {{# layui.each(d.options, function(index, item){ }}            
            <li>
                <a value="{{item.value}}" {{# if(item.hasOwnProperty("disabled")){ }}disabled="true"{{# } }}  {{# if(item.hasOwnProperty("readonly")){ }}readonly="true"{{# } }} >
                    <span class="layui-icon layui-anim"></span>
                    <b>{{item.title}}</b>
                </a>
            </li>
            {{# }); }}
        </ul>
    </div>
</script>
        `);

        //点击
        layui.jquery(document).delegate(".jsonui_checkbox li a", 'click', function (e) {
            let disabled = layui.jquery(this).attr("disabled");
            let readonly = layui.jquery(this).attr("readonly");
            if (disabled || readonly) {
                return false;
            }

            //获取module
            let module = jsonui.parser.tool.getModule(layui.jquery(this));

            //用户点击的选项值
            let value = layui.jquery(this).attr("value");
            //旧选项值
            let checkbox_value = layui.jquery(this).parent().parent().siblings("input").val().split(",");
            //是否旧数据选中（默认未选中）
            let is_exist = false;
            //新选项值
            let new_checkbox_value = [];
            //计算点击后的新选项值
            layui.each(checkbox_value, function (index, item) {
                if (value == item) {
                    is_exist = true;
                    return false;
                }
                if (item.length) {
                    new_checkbox_value.push(item);
                }
            });
            if (is_exist === false) {
                new_checkbox_value.push(value);
            }

            //如果当前选项被选中
            if (is_exist === false) {
                //获取点击的选项json对象
                let option = false;
                layui.each(module.data.options, function (index, item) {
                    if (value == item.value) {
                        option = item;
                    }
                });
                //如果有共存选项
                if (option && option.hasOwnProperty("coe")) {

                    let coe_checkbox_value = [];
                    //option.coe = option.coe.split(",");
                    //console.log(new_checkbox_value);
                    //console.log(option.coe.split(","));
                    //循环新选项值
                    layui.each(new_checkbox_value, function (index, item) {

                        //只有自己选项和共存选项可以被选中
                        if (value == item || jsonui.parser.json.contain(option.coe.split(","), item)) {
                            coe_checkbox_value.push(item);
                        }
                    });
                    new_checkbox_value = coe_checkbox_value;
                }
            }

            new_checkbox_value = new_checkbox_value.toString();
            //设置input值
            layui.jquery(this).parent().parent().siblings("input").val(new_checkbox_value);
            //复选框读取
            checkbox_read(module, new_checkbox_value);
        });
    },

    render: function (module) {
        layui.use(["laytpl"], function () {
            layui.laytpl(layui.jquery("#tpl-checkbox").html()).render(module.data, function (html) {
                module.elem.html(html);
            });
        });
    },

    setValue: function (module, values) {
        if (values.hasOwnProperty(module.data.name)) {
            //复选框读取
            checkbox_read(module, values[module.data.name]);
        }
    }
};


/**
 * 复选框读取
 * @param module
 * @param value
 */
function checkbox_read(module, value) {
    let elem = module.elem.find(".jsonui_checkbox");
    let value_arr = value.split(",");
    let elem_lis = elem.children("ul").children("li");
    layui.each(elem_lis, function (index, item) {
        let self_elem = elem_lis.eq(index);
        let self_value = self_elem.children("a").attr("value");
        let self_icon = self_elem.children("a").children("span.layui-icon");
        if (jsonui.parser.json.contain(value_arr, self_value)) {
            self_icon.addClass("layui-icon-ok").addClass("layui-anim-scalesmall-spring");
        } else {
            self_icon.removeClass("layui-icon-ok").removeClass("layui-anim-scalesmall-spring");
        }
    });
    //复选框事件
    checkbox_after(module, value);
}

/**
 * 复选框事件
 * @param module
 * @param value
 */
function checkbox_after(module, value) {
    let value_arr = value.split(",");
    //选中后事件
    let success_after = [];
    //取消后事件
    let error_after = [];
    //循环所有选项
    layui.each(module.data.options, function (index, item) {
        //是否选中
        let is_checked = false;
        for (let index1 in value_arr) {
            let item1 = value_arr[index1];
            if (item.value == item1) {
                is_checked = true;
                break;
            }
        }
        //已选中
        if (is_checked === true) {
            if (item.hasOwnProperty("successAfter") && !jsonui.parser.json.contain(success_after, item.successAfter)) {
                success_after.push(item.successAfter);
            }
        }
        //未选中
        else {
            if (item.hasOwnProperty("errorAfter") && !jsonui.parser.json.contain(error_after, item.errorAfter)) {
                error_after.push(item.errorAfter);
            }
        }
    });
    //console.log(success_after);
    //console.log(error_after);


    layui.each(error_after, function (index, item) {
        jsonui.parser.event.init(item);
    });
    layui.each(success_after, function (index, item) {
        jsonui.parser.event.init(item);
    });
}


jsonui.parser.module.code = {

    //code状态
    layuiUseCodeStatus: false,

    init: function () {

        //更新code状态
        jsonui.parser.module.code.layuiUseCodeStatus = false;

        jsonui.parser.tool.createCss(`
pre{
    background: #f7f7f7;
    color:#484848;
    padding:8px 15px;
    border-radius: 4px;
    line-height:20px;
        overflow-y: auto;
}
        `);
        jsonui.parser.tool.createTpl(`
<script type="text/html" id="tpl-code">
    <pre 
        {{# if(d.hasOwnProperty("attr") && d.attr.hasOwnProperty("height")){ }}
            lay-height="{{d.attr.height}}"
        {{# } }}
    >{{# if(d.hasOwnProperty("content")){ }}{{d.content}}{{# } }}</pre>
</script>
        `);

    },

    render: function (module) {
        layui.use(["laytpl"], function () {
            layui.laytpl(layui.jquery("#tpl-code").html()).render(module.data, function (html) {
                module.elem.html(html);
            });
        });
    },

    success: function (module) {
        //实例化layui code
        if (jsonui.parser.module.code.layuiUseCodeStatus === false) {
            layui.use('code', function () {
                layui.code();
                //更新code状态
                jsonui.parser.module.code.layuiUseCodeStatus = true;
            });
        }
    }

};


jsonui.parser.module.date = {

    init: function () {
        jsonui.parser.tool.createCss(`
.layui-input[disabled="true"]{
    background: #f6f6f6;
    cursor: not-allowed;
}
        `);
        jsonui.parser.tool.createTpl(`
<script type="text/html" id="tpl-date">
    <input
         type="text"
         name="{{d.name}}"
            {{# if(d.hasOwnProperty("placeholder")){ }}
                placeholder="{{d.placeholder}}"
    {{# } }}
    {{# if(d.hasOwnProperty("disabled")){ }}
    disabled="true"
    {{# } }}
    {{# if(d.hasOwnProperty("readonly")){ }}
    readonly="true"
    {{# } }}
    class="layui-input"
    uniqid="{{d.uniqid}}"
    />
</script>
        `);
    },

    render: function (module) {
        layui.use(["laytpl", "laydate"], function () {
            //唯一id
            module.data.uniqid = "jsonui-date-" + Number(Math.random().toString().substr(3, 10) + Date.now()).toString(36);
            layui.laytpl(layui.jquery("#tpl-date").html()).render(module.data, function (html) {
                module.elem.html(html);

                //默认参数
                let param = jsonui.parser.json.merge({
                    elem: "input[uniqid=\"" + module.data.uniqid + "\""
                }, module.data);

                layui.laydate.render(param);
            });
        });
    }
};


jsonui.parser.module.fieldSet = {

    init: function () {

        jsonui.parser.tool.createCss(`
.layui-elem-field,.layui-field-title{
    margin:0;
}
        `);
        jsonui.parser.tool.createTpl(`
<script type="text/html" id="tpl-fieldSet">
    {{# 
        let attr_class = "layui-elem-field";
        if(d.hasOwnProperty("attr") && !d.attr.hasOwnProperty("box")){
            attr_class += " layui-field-title";
        }
    }}
    <fieldset class="{{attr_class}}">
      <legend>{{d.attr.title}}</legend>
      <div class="layui-field-box">{{# if(d.hasOwnProperty("content")){ }}{{d.content}}{{# } }}</div>
    </fieldset>
</script>
        `);

    },

    render: function (module) {
        layui.use(["laytpl"], function () {
            layui.laytpl(layui.jquery("#tpl-fieldSet").html()).render(module.data, function (html) {
                module.elem.html(html);
                //更新elem
                module.elem = module.elem.children("fieldSet").children(".layui-field-box");

                //发现模块
                jsonui.parser.render.findModule({
                    data: module.data,
                    elem: module.elem
                });
            });
        });
    }

};


jsonui.parser.module.form = {


    init: function () {
        jsonui.parser.tool.createCss(`
.module-form{
    padding:15px;
    display: table;
    width: calc(100% - 30px);
}
        `);
        jsonui.parser.tool.createTpl(`
<script type="text/html" id="tpl-form">
    <form class="layui-form module-form" 
    {{# 
        if(d.hasOwnProperty("attr") && d.attr.hasOwnProperty("styleType")){
    }}
        {{# 
            if(d.attr.styleType=="lime"){
        }}
            style="background: #fbfefb;border: 1px solid #e5e8e5;"
        {{# 
            } 
        }}
    {{# 
        } 
    }}
    ></form>
</script>
        `);
    },

    render: function (module) {
        layui.use(["laytpl"], function () {
            layui.laytpl(layui.jquery("#tpl-form").html()).render(module.data, function (html) {
                module.elem.html(html);
                //更新elem
                module.elem = module.elem.children("form");
                //设置表单filter
                module.elem.attr("lay-filter", module.index);

                //发现模块
                jsonui.parser.render.findModule({
                    data: module.data,
                    elem: module.elem
                });
            });
        });
    },

    success: function (module) {
        layui.use(["form"], function () {
            //更新layui表单组件的渲染(也可以在每个模块中更新渲染，不过在此更新效率更高)
            layui.form.render();

            //如果有表单默认值
            if (module.data.hasOwnProperty("attr") && module.data.attr.hasOwnProperty("values")) {
                //直接使用数据
                if (jsonui.parser.json.isObject(module.data.attr.values)) {
                    set_form_values(module.data.attr.values);
                }
                //api接口
                else {
                    let index = layer.load(1, {shade: [0.1, "#fff"]});
                    jsonui.parser.api.ajax({
                        url: module.data.attr.values,
                        success: function (result) {
                            layer.close(index);
                            set_form_values(result.result);
                        },
                        error: function(msg){
                            layer.close(index);
                            layer.msg(msg);
                        }
                    });
                }
            }
        });

        /**
         * 设置表单默认值
         * @param values
         */
        function set_form_values(values = []) {
            //设置表单默认数据
            layui.form.val(module.index, values);

            //设置自定义模块的默认数据
            let sub_modules_index = module.elem.find(".jsonui-module");
            layui.each(sub_modules_index, function (index, item) {
                //获取module
                let sub_module = jsonui.parser.tool.getModule(sub_modules_index.eq(index));
                //调用setValue函数
                if (jsonui.parser.module[sub_module.name].hasOwnProperty("setValue")) {
                    //console.log("5————————————————————————————————————————————————————————————————设置模块默认值：" + sub_module.name);
                    jsonui.parser.module[sub_module.name].setValue(sub_module, values);
                }
            });
        }
    }
};


/**
 * 间隔槽
 * @type {{init: jsonui.parser.module.hr.init, render: jsonui.parser.module.hr.render}}
 */
jsonui.parser.module.gap = {

    init: function () {

        jsonui.parser.tool.createCss(`
.jsonui-gap{
    display:table;
    width:100%;
}
        `);
        jsonui.parser.tool.createTpl(`
<script type="text/html" id="tpl-gap">
    {{# 
        let param_color = "#fff";
        if(d.hasOwnProperty("color")){
            param_color = d.color;
        }
        let param_height = "20px";
        if(d.hasOwnProperty("height")){
            param_height = d.height;
        }
    }}
    <div class="jsonui-gap" style="background:{{param_color}};height:{{param_height}};"></div>
</script>
        `);

    },

    render: function (module) {
        layui.use(["laytpl"], function () {
            layui.laytpl(layui.jquery("#tpl-gap").html()).render(module.data, function (html) {
                module.elem.html(html);
            });
        });
    }

};


jsonui.parser.module.hr = {

    init: function () {

        jsonui.parser.tool.createCss(`
.layui-border-white{
    border-color: #ffffff !important;
    color: #ffffff !important;
}
        `);
        jsonui.parser.tool.createTpl(`
<script type="text/html" id="tpl-hr">
    {{# 
        let attr_class = "";
        if(d.hasOwnProperty("color")){
            attr_class += "layui-border-"+d.color;
        }
    }}
    <hr class="{{attr_class}}">
</script>
        `);

    },

    render: function (module) {
        layui.use(["laytpl"], function () {
            layui.laytpl(layui.jquery("#tpl-hr").html()).render(module.data, function (html) {
                module.elem.html(html);
            });
        });
    }

};


jsonui.parser.module.html = {
    init:function (){
        jsonui.parser.tool.createCss(`

        `);
        jsonui.parser.tool.createTpl(`
<script type="text/html" id="tpl-html">
{{#
    if(d.hasOwnProperty("attr")){ 
        if(d.attr.hasOwnProperty("content")){      
}}
{{d.attr.content}}
{{#
        }
    }
}}
</script>
        `);
    },

    render: function (module) {
        layui.use(["laytpl"], function () {
            layui.laytpl(layui.jquery("#tpl-html").html()).render(module.data, function (html) {
                module.elem.html(html);

                //如果有接力棒
                if(module.data.hasOwnProperty("attr")){
                    if(module.data.attr.hasOwnProperty("baton")){
                        //更新elem
                        module.elem = module.elem.find(module.data.attr.baton);

                        //发现模块
                        jsonui.parser.render.findModule({
                            data: module.data,
                            elem: module.elem
                        });
                    }
                }
            });
        });
    }
};


jsonui.parser.module.image = {
    render: function (module) {
        module.elem.html("<img src=\"" + module.data.url + "\" style=\"" + module.data.style + "\" />");
    }
};


jsonui.parser.module.imageUpload = {

    init:function (){
        jsonui.parser.tool.createCss(`
/*图片上传*/
.layui-upload-drag{
    cursor:default;
}
.jsonui_image{
    width:196px;
}
.jsonui_image .j_upload{
    cursor: pointer;
}
.jsonui_image .j_view{
    background: #fcfcfc;
    height: 120px;
    overflow: hidden;
}
.jsonui_image .j_view_table{
    display:table;
    max-width:100%;
    height: 120px;
}
.jsonui_image .j_view_content{
    display: table-cell;
    vertical-align: middle;
}
.jsonui_image .j_view_content img{
    max-width:100%;
    max-height:100%;
}
.jsonui_image .j_fun{
    height:28px;
    text-align: left;
}
.jsonui_image .j_browse,.jsonui_image .j_delete{
    display: inline-block;
    margin-right:8px;
    line-height: 28px;
    text-align: center;
    font-size: 13px;
    cursor: pointer;
    color:#666;
}
.jsonui_image .j_browse:hover,.jsonui_image .j_delete:hover{
    color: #409eff;
}
        `);
        jsonui.parser.tool.createTpl(`
<script type="text/html" id="tpl-imageUpload">
    <div class="jsonui_image layui-upload-drag" name="{{d.name}}">
        <div class="j_upload">
            <i class="layui-icon"></i>
            <p>点击上传，或将文件拖拽到此处</p>
        </div>
    </div>
</script>
        `);
    },

    render: function (module) {
        layui.use(["laytpl"], function () {
            layui.laytpl(layui.jquery("#tpl-imageUpload").html()).render(module.data, function (html) {
                module.elem.html(html);
            });
        });
    },
    success: function (module) {
        //拖拽上传
        layui.upload.render({
            elem: ".jsonui_image[name='"+module.data.name+"'] .j_upload",
            url: module.data.url,
            done: function (result) {
                layer.msg(result.msg);
                image_read(module.elem, result);
            }
        });
    },
    setValue: function (module, values) {
        if(values.hasOwnProperty(module.data.name)){
            image_read(module.elem, {result: {url: values[module.data.name]}});
        }
    }
};



/**
 * 图片读取
 * @param module_elem
 * @param result
 */
function image_read(module_elem, result = {}) {
    let elem = module_elem.find(".jsonui_image");
    let name = elem.attr("name");
    //移除元素
    if (elem.children(".j_content").size()) {
        elem.children(".j_content").remove();
    }
    //创建元素
    elem.append("<div class=\"j_content\"><hr><div class=\"j_view\"><div class=\"j_view_table\"><div class=\"j_view_content\"><img src=\"" + result.result.url + "\"><input type=\"hidden\" name=\"" + name + "\" value=\"" + result.result.url + "\" /></div></div></div><div class=\"j_fun\"><div class=\"j_browse layui-icon layui-icon-picture\">浏览</div><div class=\"j_delete layui-icon layui-icon-delete\">移除</div></div></div>");
}

//浏览图片
layui.jquery(document).delegate(".jsonui_image .j_browse", 'click', function (e) {
    let url = layui.jquery(this).parent().siblings(".j_view").find("img").attr("src");
    layer.photos({
        photos: {
            "title": "浏览图片",
            "id": 1,
            "start": 0,
            "data": [
                {
                    "alt": "",
                    "pid": 1,
                    "src": url,
                    "thumb": url
                }
            ]
        },
        anim: 5
    });
});

//移除图片
layui.jquery(document).delegate(".jsonui_image .j_delete", 'click', function (e) {
    if (confirm("确定移除吗？")) {
        layui.jquery(this).parent().parent().remove();
    }
});


jsonui.parser.module.input = {

    init:function (){
        jsonui.parser.tool.createCss(`
.layui-input[disabled="true"]{
    background: #f6f6f6;
    cursor: not-allowed;
}
        `);
        jsonui.parser.tool.createTpl(`
<script type="text/html" id="tpl-input">
    <input
         type="text"
         name="{{d.name}}"
            {{# if(d.hasOwnProperty("placeholder")){ }}
                placeholder="{{d.placeholder}}"
    {{# } }}
    {{# if(d.hasOwnProperty("disabled") && d.disabled===true){ }}
    disabled="true"
    {{# } }}
    {{# if(d.hasOwnProperty("readonly")){ }}
    readonly="true"
    {{# } }}
    class="layui-input"
    />
</script>
        `);
    },

    render: function (module) {
        layui.use(["laytpl"], function () {
            layui.laytpl(layui.jquery("#tpl-input").html()).render(module.data, function (html) {
                module.elem.html(html);
            });
        });
    }
};


jsonui.parser.module.item = {
    init:function (){
        jsonui.parser.tool.createCss(`
.layui-form-item{
    margin-bottom: 0;
    padding-bottom: 15px;
}
.layui-form-label.j_required::before{
    display: inline-block;
    margin-right: 4px;
    color: #f5222d;
    font-size: 14px;
    font-family: SimSun,sans-serif;
    line-height: 1;
    content: "*";
}
.layui-form-label.j_colon::after {
    content: ":";
    position: relative;
    top: -.5px;
    margin: 0 0px 0 2px;
}
@media screen and (max-width:450px) {
 .layui-form-item .layui-form-label {
  white-space: break-spaces;
 }
}
@media screen and (min-width:903px) {
 .layui-form-item .layui-form-label {
  width:120px;
 }
 .layui-form-item .layui-input-block {
  margin-left:150px;
 }
}
        `);
        jsonui.parser.tool.createTpl(`
<script type="text/html" id="tpl-item">
    <div class="layui-form-item">
        {{# if(d.hasOwnProperty("attr")){ 
            let attr_class = "layui-form-label";
            if(d.attr.hasOwnProperty("required")){
                attr_class += " j_required";
            }
            if(d.attr.hasOwnProperty("colon")){
                attr_class += " j_colon";
            }
        }}
        <label class="{{attr_class}}">{{d.attr.title}}</label>
        {{# } }}
        <div class="layui-input-block"></div>
    </div>
</script>
        `);
    },

    render: function (module) {
        layui.use(["laytpl"], function () {
            layui.laytpl(layui.jquery("#tpl-item").html()).render(module.data, function (html) {
                module.elem.html(html);
                //更新elem
                module.elem = module.elem.children(".layui-form-item").children(".layui-input-block");

                //发现模块
                jsonui.parser.render.findModule({
                    data: module.data,
                    elem: module.elem
                });
            });
        });
    }
};


jsonui.parser.module.linkage = {

    init:function (){
        jsonui.parser.tool.createCss(`

/*联动选择*/
.jsonui_linkage{

}
.jsonui_linkage .j_title{

}
.jsonui_linkage .j_title input{
    cursor: pointer;
}
.jsonui_linkage .j_select{
    display:none;
    position: absolute;
    z-index: 999;
    width: 400px;
    margin-top:10px;
    border: 1px solid #eee;
    border-radius: 4px;
    background-color: #fff;
    -webkit-box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}
.jsonui_linkage .j_select[select="1"]{
    display:block;
}
.jsonui_linkage[history_value] .j_select[select="1"]{
    display:none;
}
.jsonui_linkage .j_select_tab{
    min-height: 42px;
    background: #f0f0f0;
    display:table;
    width:100%;
    border-radius: 4px 4px 0 0;
}
.jsonui_linkage .j_select_tab span{
    display: block;
    float: left;
    line-height: 42px;
    padding: 0 20px;
    border-right: 1px solid #eee;
    cursor: pointer;
}
.jsonui_linkage .j_select_tab span.on{
    height: 42px;
    background: #fff;
    color: #009688;
}
.jsonui_linkage .j_select_tab span.on:first-child{
    border-radius: 4px 0 0 0;
}
.jsonui_linkage .j_select_content{
    max-height: 135px;
    margin-top:-1px;
    border-top: 1px solid #eee;
    overflow: auto;
}
.jsonui_linkage .j_select_content li{
    padding: 10px;
}
.jsonui_linkage .j_select_content li .j_load,.jsonui_linkage .j_select_content li .j_error{
    display:none;
    min-height: 115px;
}
.jsonui_linkage .j_select_content li .j_load{
    background: url("../../layui-v2.6.8/layui/css/modules/layer/default/loading-2.gif") no-repeat center center;
}
.jsonui_linkage .j_select_content li .j_error{
    line-height: 20px;
    color:#ccc;
}
.jsonui_linkage .j_select_content li .j_values{
    display:none;
}
.jsonui_linkage .j_select_content li .j_values .option{
    display: inline-block;
    color: #4D4D4D;
    padding: 0 10px;
    line-height: 30px;
    border-radius: 4px;
    cursor: pointer;
}
.jsonui_linkage .j_select_content li .j_values .option.on{
    background: #009688;
    color: #fff;
}
.jsonui_linkage .j_select_content li[status="0"] .j_load{
    display:block;
}
.jsonui_linkage .j_select_content li[status="1"] .j_values{
    display:block;
}
.jsonui_linkage .j_select_content li[status="2"] .j_error{
    display:block;
}
.jsonui_linkage .j_select_fun{
    border-top: 1px solid #eee;
    height:40px;
    padding:0 15px;
    text-align: right;
}
.jsonui_linkage .j_cancel,.jsonui_linkage .j_confirm{
    display:inline-block;
    cursor: pointer;
    padding:4px 15px;
    line-height: 20px;
    margin:6px 0 0 7px;
    border-radius: 2px;
}
.jsonui_linkage .j_cancel{
    border: 1px solid #eee;
    padding:3px 14px;
}
.jsonui_linkage .j_confirm{
    background: #009688;
    color: #fff;
}
        `);
        jsonui.parser.tool.createTpl(`
<script type="text/html" id="tpl-linkage">
    <div class="jsonui_linkage" url="{{d.url}}" min_level="{{d.minLevel}}" max_level="{{d.maxLevel}}">
        <div class="j_title">
            <input type="text" placeholder="请选择" readonly="true" class="layui-input" />
            <input type="hidden" name="{{d.name}}" />
        </div>
    </div>
</script>
        `);
    },

    render: function (module) {
        layui.use(["laytpl"], function () {
            layui.laytpl(layui.jquery("#tpl-linkage").html()).render(module.data, function (html) {
                module.elem.html(html);
            });
        });
    },
    setValue: function (module, values) {
        if(values.hasOwnProperty(module.data.name)){
            linkage_read(module.elem, values[module.data.name]);
        }
    }
};






/**
 * 联动菜单读取
 * @param module_elem
 * @param value
 */
function linkage_read(module_elem, value) {
    let elem = module_elem.find(".jsonui_linkage");
    elem.attr("history_value", value);
    elem.find("input[type=\"text\"]").trigger("focus");
}


//展开联动选择
layui.jquery(document).delegate(".jsonui_linkage .j_title input", 'focus', function (e) {
    layui.jquery(this).blur();
    let select = layui.jquery(this).parent().parent().children(".j_select").attr("select");
    if (!select) {
        let elem = layui.jquery(this).parent().parent();
        //加载面板
        elem = load_panel(elem);
        //展开并获取选项卡数量
        let tab_size = elem.children(".j_select").attr("select", "1").children(".j_select_tab").find("span").size();
        if (!tab_size) {

            //加载选项列表
            load_select(elem, 0);
        }
    }
    return false;

    //加载面板
    function load_panel(elem) {
        if (!elem.children(".j_select").size()) {
            elem.append("<div class=\"j_select layui-anim layui-anim-upbit\"><div class=\"j_select_tab\"></div><div class=\"j_select_content\"></div><div class=\"j_select_fun\"><div class=\"j_cancel\">取消</div><div class=\"j_confirm\">确定</div></div></div>");
            return elem.children().parent();
        }
        return elem;
    }
});

//关闭联动选择
layui.jquery(document).mousedown(function (e) {
    var _con = layui.jquery('.j_select[select="1"]');
    if (!_con.is(e.target) && _con.has(e.target).length === 0) {
        layui.jquery('.j_select[select="1"]').removeAttr("select");
    }
});

//选择选项
layui.jquery(document).delegate(".jsonui_linkage .j_select_content li .option", 'click', function (e) {
    let parent_id = layui.jquery(this).parent().parent().attr("parent_id");
    let id = layui.jquery(this).attr("data_id");
    let title = layui.jquery(this).html();
    let tab_elem = layui.jquery(this).parent().parent().parent().parent().children(".j_select_tab").find(".on");
    let tab_index = tab_elem.index();
    let tab_size = tab_elem.parent().children().size();
    //设置选项
    layui.jquery(this).addClass("on").siblings().removeClass("on");
    //设置当前选项卡值
    tab_elem.html(title).attr("data_id", id);
    //将当前选项卡后面的选项卡删除
    for (let i = tab_size; i > 0; i--) {
        if (i > tab_index) {
            tab_elem.parent().children().eq(i).remove();
        } else {
            break;
        }
    }
    //加载选项列表
    load_select(layui.jquery(this).parent().parent().parent().parent().parent(), id);
});

//点击选项卡
layui.jquery(document).delegate(".jsonui_linkage .j_select_tab span", 'click', function (e) {
    let parent_id = layui.jquery(this).attr("parent_id");
    //设置选项卡
    layui.jquery(this).addClass("on").siblings().removeClass("on");
    //设置选项
    layui.jquery(this).parent().siblings(".j_select_content").children("li").css("display", "none").parent().children("li[parent_id=\"" + parent_id + "\"]").css("display", "block");
});

//点击确定
layui.jquery(document).delegate(".jsonui_linkage .j_confirm", 'click', function (e) {
    let tab_elem = layui.jquery(this).parent().parent().children(".j_select_tab").children();
    let text_elem = layui.jquery(this).parent().parent().parent().children(".j_title").children("input[type=\"text\"]");
    let hidden_elem = text_elem.siblings("input[type=\"hidden\"]");
    let size = tab_elem.size();
    let value = "";
    let title = ""
    for (let i = 0; i < size; i++) {
        let item_id = tab_elem.eq(i).attr("data_id");
        let item_title = tab_elem.eq(i).html();
        if (item_id) {
            value += (value) ? "," + item_id : item_id;
            title += (title) ? "/" + item_title : item_title;
        }
    }
    text_elem.val(title);
    hidden_elem.val(value);
    layui.jquery(this).parent().parent().removeAttr("select");
});

//点击取消
layui.jquery(document).delegate(".jsonui_linkage .j_cancel", 'click', function (e) {
    if (confirm("确定取消吗？")) {
        let select_elem = layui.jquery(this).parent().parent();
        let text_elem = select_elem.siblings(".j_title").children("input[type=\"text\"]");
        let hidden_elem = text_elem.siblings("input[type=\"hidden\"]");
        text_elem.val("");
        hidden_elem.val("");
        select_elem.remove();
    }
});

//加载选项列表
function load_select(elem, parent_id = 0) {
    //alert(parent_id);

    let url = elem.attr("url");
    let min_level = elem.attr("min_level");
    let max_level = elem.attr("max_level");
    let elem_tab = elem.children(".j_select").children(".j_select_tab");
    let elem_content = elem.children(".j_select").children(".j_select_content");
    let elem_confirm = elem.children(".j_select").find(".j_confirm");
    let level = elem_tab.children().size();

    //到达最小等级
    if (level >= min_level) {
        elem_confirm.css("display", "inline-block");
    } else {
        elem_confirm.css("display", "none");
    }
    //到达最大等级
    if (level == max_level) {
        elem.removeAttr("history_value");
        elem_confirm.click();
        return false;
    }

    //取消选项卡选项
    elem_tab.children("span").removeClass("on");
    //创建选项卡
    elem_tab.append("<span class=\"on\" parent_id=\"" + parent_id + "\">请选择</span>");
    //隐藏所有选项
    elem_content.children("li").css("display", "none");

    //判断是否已加载过选项
    let is_li = elem_content.children("li[parent_id=\"" + parent_id + "\"]").size();
    if (is_li) {
        elem_content.children("li[parent_id=\"" + parent_id + "\"]").css("display", "block");
    }
    //没有加载过
    else {
        //创建选项
        elem_content.append("<li parent_id=\"" + parent_id + "\"><div class=\"j_load\"></div><div class=\"j_error\"></div><div class=\"j_values\"></div></li>");
        //当前li选项
        let li_elem = elem_content.children("li[parent_id=\"" + parent_id + "\"]");
        //更新状态
        li_elem.attr("status", 0);
        //拉取选项
        jsonui.parser.api.ajax({
            url: url,
            method: "GET",
            data: {
                parent_id: parent_id
            },
            success: function (result) {
                //有数据
                if (result.result.data.length) {
                    //拉取成功
                    li_elem.attr("status", 1);
                    //渲染选项值
                    for (let index in result.result.data) {
                        let item = result.result.data[index];
                        //title兼容name方案
                        if (!item.hasOwnProperty("title") && item.hasOwnProperty("name")) {
                            item.title = item.name;
                        }
                        li_elem.children(".j_values").append("<div class=\"option\" data_id=\"" + item.id + "\">" + item.title + "</div>");
                    }
                    //执行读取过程
                    {
                        let history_value = elem.attr("history_value");
                        if (history_value) {
                            //从history_value获取本次要点击的id,并更新history_value
                            history_value = history_value.split(",");
                            let data_id = history_value[0];
                            delete history_value[0];
                            let new_history_value = [];
                            let key = 0;
                            for (let i in history_value) {
                                new_history_value[key] = history_value[i];
                                key++;
                            }
                            history_value = new_history_value.toString();
                            //对本次要点击的id进行操作
                            let option_elem = li_elem.children(".j_values").children(".option[data_id=\"" + data_id + "\"]");
                            if (option_elem.size()) {
                                elem.attr("history_value", history_value);
                                option_elem.click();
                                //如果选完了
                                if (!history_value) {
                                    elem.removeAttr("history_value");
                                    elem_confirm.click();
                                }
                            }
                            //如果找不到id
                            else {
                                elem.removeAttr("history_value");
                                elem_confirm.click();
                            }
                        }
                    }
                }
                //无数据
                else {
                    li_elem.attr("status", 2).find(".j_error").html("无数据");
                }
            },
            error: function (msg) {
                //拉取失败
                li_elem.attr("status", 2).find(".j_error").html(msg);
            }
        });
    }
}


jsonui.parser.module.menu = {

    init:function (){
        jsonui.parser.tool.createCss(`
.layui-menu li{
    width:100%;
    margin:0;
}
.layui-menu{
    margin:0;
}
        `);
        jsonui.parser.tool.createTpl(`
<script type="text/html" id="tpl-menu">
    <ul class="layui-menu">
        {{# layui.each(d, function(index, item){ }}
            {{# if(item.parentId==0){ }}
                {{# if(item.children===false){ }}
                    <li index="{{index}}">
                        <div class="layui-menu-body-title">
                            {{item.title}}
                        </div>
                    </li>
                    <li class="layui-menu-item-divider"></li>
                {{# }else{ }}
                    <li class="layui-menu-item-group layui-menu-item-down" lay-options="{type: 'group'}">
                        <div class="layui-menu-body-title">
                            {{item.title}}<i class="layui-icon layui-icon-up"></i>
                        </div>
                        <ul>
                            {{# layui.each(d, function(index1, item1){ }}
                                {{# if(item1.parentId==item.id){ }}
                                <li index="{{index1}}">
                                    <div class="layui-menu-body-title">
                                        {{item1.title}}
                                    </div>
                                </li>
                                {{# } }}
                            {{# }); }}
                        </ul>
                    </li>
                    <li class="layui-menu-item-divider"></li>
                {{# } }}
            {{# } }}
        {{# }); }}
    </ul>
</script>
        `);


        //点击菜单
        layui.jquery(document).delegate(".jsonui-module>.layui-menu li", 'click', function (e) {
            //阻止冒泡
            e.stopPropagation();
            //获取菜单index
            let index = layui.jquery(this).attr("index");
            if (!index) return false;
            //获取module
            let module = jsonui.parser.tool.getModule(layui.jquery(this));
            //打开一个菜单
            jsonui.parser.open.init(module.data[index].window);
        });
    },

    render: function (module) {
        //下级缺省值处理（由于需要break，故此处不适用layui.each）
        for (let index in module.data) {
            let item = module.data[index];
            //缺省id
            item.id = (item.hasOwnProperty("id")) ? item.id : -1;
            //下级
            item["children"] = false;
            for (let index1 in module.data) {
                let item1 = module.data[index1];
                //缺省parentId
                item1.parentId = (item1.hasOwnProperty("parentId")) ? item1.parentId : 0;
                //如果有下级
                if (item.id == item1.parentId) {
                    item["children"] = true;
                    break;
                }
            }
        }

        layui.use(["laytpl"], function () {
            layui.laytpl(layui.jquery("#tpl-menu").html()).render(module.data, function (html) {
                module.elem.html(html);
            });
        });
    }
};


jsonui.parser.module.part = {

    init: function () {

        jsonui.parser.tool.createCss(`
.part{
    padding:5px 0;
    line-height:24px;
}
        `);
        jsonui.parser.tool.createTpl(`
<script type="text/html" id="tpl-part">
    <div class="part">{{d.content}}</div>
</script>
        `);

    },

    render: function (module) {
        layui.use(["laytpl"], function () {
            layui.laytpl(layui.jquery("#tpl-part").html()).render(module.data, function (html) {
                module.elem.html(html);
            });
        });
    }

};


jsonui.parser.module.point = {

    init: function () {

        jsonui.parser.tool.createCss(`
.point{}
.point a{
    position: absolute;
    color: #2d8cf0;
    display:none;
}
.point:hover a{display: inline-block;}
.point[h="1"],.point[h="1"] a{font-size:24px;height:26px;line-height:26px;}
.point[h="2"],.point[h="2"] a{font-size:20px;height:22px;line-height:22px;}
.point[h="3"],.point[h="3"] a{font-size:18px;height:20px;line-height:20px;}
.point[h="4"],.point[h="4"] a{font-size:16px;height:18px;line-height:18px;}
.point[h="5"],.point[h="5"] a{font-size:14px;height:16px;line-height:16px;}
.point[h="6"],.point[h="6"] a{font-size:12px;height:14px;line-height:14px;}
.point[h="1"] a{width:26px;margin-left:-26px;}
.point[h="2"] a{width:22px;margin-left:-22px;}
.point[h="3"] a{width:20px;margin-left:-20px;}
.point[h="4"] a{width:18px;margin-left:-18px;}
.point[h="5"] a{width:16px;margin-left:-16px;}
.point[h="6"] a{width:14px;margin-left:-14px;}
        `);
        jsonui.parser.tool.createTpl(`
<script type="text/html" id="tpl-point">
    {{# 
        let point_span_style = "";
        if(d.hasOwnProperty("align")){
            point_span_style += "text-align: "+d.align+";";
        }
        if(d.hasOwnProperty("padding")){
            point_span_style += "padding: "+d.padding+";";
        }
        else{
            point_span_style += "padding: 20px 0;";
        }
    }}
    <div class="point" style="{{point_span_style}}" h="{{d.h}}"><a href="#{{d.name}}" id="{{d.name}}">#</a>{{d.name}}</div>
</script>
        `);

    },

    render: function (module) {
        layui.use(["laytpl"], function () {
            layui.laytpl(layui.jquery("#tpl-point").html()).render(module.data, function (html) {
                module.elem.html(html);
            });
        });
    }

};


/**
 * jsonui-解析器-模块-打印
 * @type {{render: jsonui.parser.module.print.render}}
 */
jsonui.parser.module.print = {
    render: function (module) {
        module.elem.html(module.data);
    }
};


jsonui.parser.module.radio = {

    init:function (){
        jsonui.parser.tool.createCss(`

        `);
        jsonui.parser.tool.createTpl(`
<script type="text/html" id="tpl-radio">
    {{# layui.each(d.options, function(index, item){ }}
    <input type="radio" name="{{d.name}}" value="{{item.value}}" title="{{item.title}}" {{# if(item.hasOwnProperty("disabled")){ }}disabled="true"{{# } }} >
    {{# }); }}
</script>
        `);
    },

    render: function (module) {
        layui.use(["laytpl"], function () {
            layui.laytpl(layui.jquery("#tpl-radio").html()).render(module.data, function (html) {
                module.elem.html(html);
            });
        });
    }
};


jsonui.parser.module.select = {

    init:function (){
        jsonui.parser.tool.createCss(`

        `);
        jsonui.parser.tool.createTpl(`
<script type="text/html" id="tpl-select">
    <select name="{{d.name}}" {{# if(d.hasOwnProperty("disabled")){ }}disabled="true"{{# } }}>
        <option value="">请选择</option>
        {{# layui.each(d.options, function(index, item){ }}
        <option value="{{item.value}}" {{# if(item.hasOwnProperty("disabled")){ }}disabled="true"{{# } }} >{{item.title}}</option>
        {{# }); }}
    </select>
</script>
        `);
    },

    render: function (module) {
        layui.use(["laytpl"], function () {
            layui.laytpl(layui.jquery("#tpl-select").html()).render(module.data, function (html) {
                module.elem.html(html);
            });
        });
    }
};


jsonui.parser.module.table = {

    init: function () {
        jsonui.parser.tool.createCss(`

/*
.layui-table td,
.layui-table th,
.layui-table-col-set,
.layui-table-fixed-r,
.layui-table-grid-down,
.layui-table-header,
.layui-table-page,
.layui-table-tips-main,
.layui-table-tool,
.layui-table-total,
.layui-table-view,
.layui-table[lay-skin="line"],
.layui-table[lay-skin="row"]
{
    border-color: #409eff;
}*/

.layui-table-tool,
.layui-table-view
{
    border:none;
    margin:0;
    padding-top: 8px;
}
.layui-table-tool{
    padding:10px 0;
}

/*
.layui-table tbody tr:hover,
.layui-table thead tr,
.layui-table-click,
.layui-table-header,
.layui-table-hover,
.layui-table-mend,
.layui-table-patch,
.layui-table-tool,
.layui-table-total,
.layui-table-total tr,
.layui-table[lay-even] tr:nth-child(2n)
{
    background-color: #FAFAFA;
}*/
.layui-table thead tr,
.layui-table-header,
.layui-table-tool
{
    background: none;
}

.layui-laypage .layui-laypage-curr .layui-laypage-em {
    /*background-color: #409eff;*/
}
.layui-table-box{
    /*margin: 0 15px 15px 15px;*/
    border: 1px solid #eee;
}
.layui-table-page{
    border: none;
    border-top: 1px solid #eee;
}
.layui-table-tips-main{
    overflow-y: auto;
}


.layui-btn-tool{
    border: 1px solid #eee;
    padding: 3px 12px;
    display: inline-block;
    cursor: pointer;
    line-height: 20px;
    margin: 0px 7px 0 0;
    border-radius: 2px;
}
.layui-table-btn-lime{
    display: inline-block;
    margin: 0 0 0 0;
    border: 1px solid #a8c285;
    background-image: linear-gradient(to bottom,#fcfcfc, #f0f0f0);
    border-radius: 3px;
    padding: 0 10px;
    min-width:80px;
    height: 32px;
    line-height: 30px;
    text-align: center;
    font-size: 15px;
    color: #507a14;
}
.layui-table-btn-lime:hover{
    color: #507a14;
    opacity: 0.8;
}
.layui-table-btn-lime-tool{
    height:24px;
    line-height:22px;
    font-size:13px;
    padding:0 10px;
    min-width:50px;
}
.layui-laypage-curr em{
    color: #507a14 !important;
}
.layui-laypage-em{
    background-image: linear-gradient(to bottom,#cff483, #a1d864);
    
}
        `);
        jsonui.parser.tool.createTpl(`
<script type="text/html" id="tpl-table">
    <table class="layui-hide"></table>
</script>

<!--数据表格-模块工具栏模板-->
<script type="text/html" id="table_toolbar_tpl">
    {{#
    let toolbarData = {};
    if(!d.hasOwnProperty("LAY_COL")){
    toolbarData = jsonui.parser.json.merge({},d.toolbarData);
    }
    else{
    if(d.LAY_COL.hasOwnProperty("toolbarData")){
    toolbarData = d.LAY_COL.toolbarData;
    }
    if(d.hasOwnProperty("toolbarData")){
    toolbarData = d.toolbarData;
    }
    }
    layui.each(toolbarData, function(index, item){
    }}
    {{# if(index=="menu"){}}
    <!--菜单-->
    {{# layui.each(item, function(index1, item1){ }}
    
    
    {{# if(!d.hasOwnProperty("LAY_COL")){ }}
    <a 
        class="layui-btn layui-table-btn-lime {{# if(item1.hasOwnProperty("disabled")){ }}layui-btn-disabled{{# } }}" 
        lay-event="{{index1}}" 
        {{# if(item1.hasOwnProperty("disabled")){ }}
        disabled="true"
        {{# } }}
        >{{item1.title}}</a>
    {{# }else{ }}
    <a 
        class="layui-btn-tool layui-table-btn-lime layui-table-btn-lime-tool {{# if(item1.hasOwnProperty("disabled")){ }}layui-btn-disabled{{# } }}" 
        lay-event="{{index1}}" 
        {{# if(item1.hasOwnProperty("disabled")){ }}
        disabled="true"
        {{# } }}
        >{{item1.title}}</a>
    {{# } }}
    {{# }); }}
    {{# } }}

    {{# }); }}
</script>

<!--数据表格-状态模板-->
<script type="text/html" id="table_status_tpl">
    {{#
    let value = d[d.LAY_COL.field];
    }}
    {{# layui.each(d.LAY_COL.templetData.rule, function(index, item){ }}
    {{# if(item.code==value){ }}
    <span style="{{item.style}}">{{item.title}}</span>
    {{# } }}
    {{# }); }}
</script>

<!--数据表格-用户模板-->
<script type="text/html" id="table_user_tpl">
    {{#
    let value = d[d.LAY_COL.field];
    }}
    {{# if(value){ }}
    <div class="table_user">
        <div class="j_title"><i class="layui-icon layui-icon-user"></i>{{value.nickname}}</div>
        <div class="j_content">

        </div>
    </div>
    {{# }else{ }}
    无
    {{# } }}
</script>
        `);
    },

    render: function (module) {
        layui.use(["laytpl"], function () {
            layui.laytpl(layui.jquery("#tpl-table").html()).render({}, function (html) {
                //生成表格容器
                module.elem.html(html);
                module.elem.children("table").attr("lay-filter", module.index);
                //创建表格
                table_display_create(module.data, module.index);
            });
        });
    }
};


/**
 * 创建数据表格的参数，每次创建表格时会将参数存在这里，便于重载表格。
 * @type {{}}
 */
var table_display_param = {};

/**
 * 创建数据表格
 * @param param
 * @param module_index
 */
function table_display_create(param, module_index) {

    //合并参数
    param = jsonui.parser.json.merge({
        parseData: function (result) {
            return {
                code: result.code,
                msg: result.msg,
                count: result.result.total,
                data: result.result.data
            };
        },
        moduleIndex: module_index
    }, param);

    //单独引用elem
    let elem = param.elem;

    //存储到全局变量，用于本窗口或其他窗口调用表格重载
    table_display_param[elem] = param;

    //删除唯一内存
    param = jsonui.parser.json.merge({}, param);

    //加强元素ID
    param["elem"] = "table.layui-hide[lay-filter=\"" + module_index + "\"]";

    layui.use(["table"], function () {
        //数据表格
        let table = layui.table;

        //载入表格
        table.render(param);

        //console.log("载入表格："+elem);

        //监听工具栏
        table.on("toolbar(" + module_index + ")", function (obj) {

            //屏蔽右上角菜单
            if (isNaN(obj.event)) {
                return false;
            }

            //取得菜单
            let this_window = {};
            for (let index in obj.config.toolbarData.menu) {
                if (index == obj.event) {
                    this_window = obj.config.toolbarData.menu[index].window;
                }
            }
            //删除唯一内存
            this_window = JSON.parse(JSON.stringify(this_window));

            //表格选项值
            let tableCheck = "";
            //如果需要表格选项
            if (this_window.hasOwnProperty("tableCheck")) {
                //取得选中项
                let checkStatus = table.checkStatus(obj.config.id);
                for (let index in checkStatus.data) {
                    let item = checkStatus.data[index];
                    tableCheck += (tableCheck) ? "," : "";
                    tableCheck += item[this_window.tableCheck];
                }
            }
            //如果表格选项值为必选
            if (this_window.hasOwnProperty("tableCheckRequired")) {
                if (this_window.tableCheckRequired === true && tableCheck==="") {
                    layer.msg('请选择数据');
                    return false;
                }
            }
            //处理url(暂时先用固定传参形式实现，后面改成变量解析形式)
            this_window.content += "?check=" + tableCheck;

            //打开页面
            jsonui.parser.open.init(this_window);
        });

        //监听工具条
        table.on("tool(" + module_index + ")", function (obj, obj_table = table_display_param[elem]) {
            //获取工具条数据
            let toolbarData = {};
            //优先使用数据表格接口中的
            if (obj.data.hasOwnProperty("toolbarData")) {
                toolbarData = obj.data.toolbarData;
            }
            //从初始工具条中获取
            else {
                let key = layui.jquery
                (obj.tr[1]).children("td").attr("data-key").split("-");
                for (let index in obj_table.cols) {
                    if (index != key[1]) {
                        continue;
                    }
                    let item = obj_table.cols[index];
                    for (let index1 in item) {
                        if (index1 != key[2]) {
                            continue;
                        }
                        let item1 = item[index1];
                        toolbarData = item1.toolbarData;
                        break;
                    }
                }
            }

            //取得菜单
            let this_window = {};
            for (let index in toolbarData.menu) {
                if (index == obj.event) {
                    this_window = toolbarData.menu[index].window;
                }
            }
            //删除唯一内存
            this_window = JSON.parse(JSON.stringify(this_window));

            //表格选项值
            let tableCheck = "";
            //如果需要表格选项
            if (this_window.hasOwnProperty("tableCheck")) {
                tableCheck = obj.data[this_window.tableCheck];
            }
            //处理url
            this_window.content += "?check=" + tableCheck;

            //打开页面
            jsonui.parser.open.init(this_window);
        });

    });
}

/**
 * 数据表格重载
 * @param elem
 */
function table_display_render(elem = "") {
    //找到elem指定的数据表格
    layui.each(table_display_param, function (index, item) {
        if (item.elem == elem) {
            //创建表格
            table_display_create(item, item.moduleIndex);
        }
    });
}


jsonui.parser.module.textarea = {
    init:function (){
        jsonui.parser.tool.createCss(`
.layui-textarea[disabled="true"]{
    background: #f6f6f6;
    cursor: not-allowed;
}
        `);
        jsonui.parser.tool.createTpl(`
<script type="text/html" id="tpl-textarea">

    <textarea
            class="layui-textarea"
            name="{{d.name}}"
            {{# if(d.hasOwnProperty("placeholder")){ }}
    placeholder="{{d.placeholder}}"
    {{# } }}
    {{# if(d.hasOwnProperty("disabled")){ }}
    disabled="true"
    {{# } }}
    {{# if(d.hasOwnProperty("readonly")){ }}
    readonly="true"
    {{# } }}
    ></textarea>
</script>
        `);
    },
    render: function (module) {
        layui.use(["laytpl"], function () {
            layui.laytpl(layui.jquery("#tpl-textarea").html()).render(module.data, function (html) {
                module.elem.html(html);
            });
        });
    }
};


jsonui.parser.module.tips = {

    init: function () {

        jsonui.parser.tool.createCss(`
/*
normal
warning
success
error
*/
.jsonui-tips{
    margin-top:5px;
    padding: 6px 15px;
    line-height:20px;
    color: rgba(0,0,0,.65);
    font-size: 14px;
    border-radius: 2px;
    border: 1px solid #eee;
    background-color: #fdfdfd;
}
.jsonui-tips-warning{
    background-color: #fffbe6;
    border: 1px solid #ffe58f;
}
.jsonui-tips-success{
    background-color: #F0FBF3;
    border: 1px solid #5FB878;
}
.jsonui-tips-error{
    color:#f5222d;
    border-color: #f5222d;
    background: #fff1f0;
}
.jsonui-tips.layui-icon::before{
    padding-right:2px;
}
        `);
        jsonui.parser.tool.createTpl(`
<script type="text/html" id="tpl-tips">
    {{# 
        let attr_class = "jsonui-tips";
        if(d.hasOwnProperty("attr") && d.attr.hasOwnProperty("type")){
            attr_class += " jsonui-tips-"+d.attr.type;
        }
        if(d.hasOwnProperty("attr") && d.attr.hasOwnProperty("icon")){
            attr_class += " layui-icon layui-icon-"+d.attr.icon;
        }
    }}
    <div class="{{attr_class}}">{{# if(d.hasOwnProperty("content")){ }}{{d.content}}{{# } }}</div>
</script>
        `);

    },

    render: function (module) {
        layui.use(["laytpl"], function () {
            layui.laytpl(layui.jquery("#tpl-tips").html()).render(module.data, function (html) {
                module.elem.html(html);
                //更新elem
                module.elem = module.elem.children(".jsonui-tips");
            });
        });
    }


};


jsonui.parser.module.title = {
    render: function (module) {
        document.title = module.data;
    }
};


